package chat

import (
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/app"
	"sweetsunnyflower/pkg/database"
	"sweetsunnyflower/pkg/paginator"

	"github.com/gin-gonic/gin"
)

func Get(idstr string) (chat Chat) {
	database.DB.Where("id", idstr).First(&chat)
	return
}

func GetBy(field, value string) (chat Chat) {
	database.DB.Where("? = ?", field, value).First(&chat)
	return
}

func All() (chats []Chat) {
	database.DB.Find(&chats)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(Chat{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func Paginate(c *gin.Context, perPage int) (chats []Chat, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(Chat{}),
		&chats,
		app.V1URL(database.TableName(&Chat{})),
		perPage,
	)
	return
}

func GetByLatestId(query requests.ChatsQueryRequest) (chats []Chat) {

	model := database.DB.Preload("User")

	if query.LatestId > 0 {
		model = model.Where("id < ?", query.LatestId)
	}

	model.Order("id desc").Limit(query.Limit).Find(&chats)

	return
}

func GetByID(id uint64) (chat Chat) {
	database.DB.Where("id", id).Preload("User").First(&chat)
	return
}
